package com.sunnyweather.android.ui.weather

import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.sunnyweather.android.R
import com.sunnyweather.android.logic.model.Weather
import com.sunnyweather.android.logic.model.getSky
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.forecast.*
import kotlinx.android.synthetic.main.life_index.*
import kotlinx.android.synthetic.main.now.*
import java.text.SimpleDateFormat
import java.util.*

class WeatherActivity : AppCompatActivity() {
    //手动刷新天气功能实现开始
    val viewModel by lazy { ViewModelProviders.of(this).get(WeatherViewModel::class.java) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT >= 21) {
            val decorView = window.decorView
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            window.statusBarColor = Color.TRANSPARENT
        }
        setContentView(R.layout.activity_weather)
        if (viewModel.locationId.isEmpty()) {
            viewModel.locationId = intent.getStringExtra("location_id") ?: ""
        }
        if (viewModel.placeName.isEmpty()) {
            viewModel.placeName = intent.getStringExtra("place_name") ?: ""
        }
        viewModel.weatherLiveData.observe(this, Observer { result ->
            val weather = result.getOrNull()
            if (weather != null) {
                showWeatherInfo(weather)
            } else {
                Toast.makeText(this, "无法成功获取天气信息", Toast.LENGTH_SHORT).show()
                result.exceptionOrNull()?.printStackTrace()
            }
            //请求结束后，隐藏刷新进度条
            swipeRefresh.isRefreshing = false
        })
        //设置下拉刷新进度条的颜色，我们就使用colors.xml中的colorPrimary作为进度条的颜色
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary)
        refreshWeather()
        //设置下拉刷新监听器，当触发下拉刷新操作时，在监听器的回调中调用refreshWeather()方法
        swipeRefresh.setOnRefreshListener {
            refreshWeather()
        }
        //手动刷新功能实现结束

        //划动菜单的逻辑处理
        //在切换城市的按钮点击事件中调用drawerLayout.openDrawer()方法来打开划动菜单
        navBtn.setOnClickListener {
            drawerLayout.openDrawer(GravityCompat.START)
        }
        //添加监听事件，监听drawerLayout的状态，当滑动菜单被隐藏起来的时候，同时也隐藏起输入法
        drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerStateChanged(newState: Int) {}

            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}

            override fun onDrawerOpened(drawerView: View) {}

            override fun onDrawerClosed(drawerView: View) {
                val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager.hideSoftInputFromWindow(drawerView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        })
    }
    //手动刷新天气部分功能实现
    fun refreshWeather() {
        viewModel.refreshWeather(viewModel.locationId)
        swipeRefresh.isRefreshing = true
        //让下拉刷新进度条显示出来
    }
    //展示天气预报数据和天气实时数据
    private fun showWeatherInfo(weather: Weather) {
        placeName.text = viewModel.placeName
        val realtime = weather.realtime
        val daily = weather.daily
        // 填充now.xml布局中数据
        val currentTempText = "${realtime.temp.toInt()} ℃"
        currentTemp.text = currentTempText
        currentSky.text = realtime.text
        val currentPM25Text = "相对湿度 ${realtime.humidity}"
        currentAQI.text = currentPM25Text
        nowLayout.setBackgroundResource(getSky(realtime.icon).bg)
        Log.d("MainActivity","dd is ${realtime.icon} and${getSky(realtime.icon).bg} and ${getSky(realtime.icon).info}")
        // 填充forecast.xml布局中的数据
        forecastLayout.removeAllViews()
        val days = 10
        for (i in 0 until days) {
            val view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false)
            val dateInfo = view.findViewById(R.id.dateInfo) as TextView
            val skyIcon = view.findViewById(R.id.skyIcon) as ImageView
            val skyInfo = view.findViewById(R.id.skyInfo) as TextView
            val temperatureInfo = view.findViewById(R.id.temperatureInfo) as TextView


            Log.d("MainActivity","Date is  ${daily[i].fxDate}")
            dateInfo.text = daily[i].fxDate
            val sky = getSky(daily[i].iconDay.toInt())
            skyIcon.setImageResource(sky.icon)
            skyInfo.text = sky.info
            val tempText = "${daily[i].tempMin.toInt()} ~ ${daily[i].tempMax.toInt()} ℃"
            temperatureInfo.text = tempText
            forecastLayout.addView(view)
        }
        // 填充life_index.xml布局中的数据
        //四方格
        windDir.text = realtime.windDir
        windScale.text = realtime.windScale
        pressure.text = realtime.pressure
        vis.text = realtime.vis


        weatherLayout.visibility = View.VISIBLE
    }

}
